package com.code4hire.desktop.converter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Handbrake {

    public static void main(String[] argse) throws IOException {
        List<String> args = new ArrayList<String>();

        System.out.println(argse[0]);

        args.add(argse[0]);
        // args.add("wine /home/mile/workspace/video/handbrake-cli_0.9.6ppa2~lucid1_i386/usr/bin/HandBrakeCLI");

        args.add("-i");
        args.add(argse[1]);// "/home/mile/1.flv");

        args.add("-o");
        args.add(argse[2]);// "/home/mile/1.mp4");

        ProcessBuilder builder = new ProcessBuilder(args);
        Process handbrakeProcess = builder.start();

        BufferedReader in = new BufferedReader(new InputStreamReader(handbrakeProcess.getInputStream()));
        String line;

        System.out.println();
        Pattern hbOutputPattern = Pattern.compile("^Encoding.*$");

        StringBuffer argsString = new StringBuffer();
        for (String arg : args) {
            if (arg.indexOf(" ") > 0) {
                arg = "\"" + arg + "\"";
            }

            argsString.append(arg);
            if (arg != args.get(args.size() - 1)) {
                argsString.append(" ");
            }
        }

        System.out.println("Options: " + argsString.toString());

        Matcher m;
        try {
            System.out.println();
            while ((line = in.readLine()) != null) {
                // System.out.println(line);
                m = hbOutputPattern.matcher(line);
                if (m.matches()) {
                    System.out.print("\r>>>" + line);
                }
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }

        }
        System.out.println("kraj");

        try {
            handbrakeProcess.waitFor();
        } catch (InterruptedException e) {
            throw new RuntimeException("Encoding was interrupted...", e);
        }

    }
}
